//
//  SalaryModel.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/24.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire

class SalaryModel: NSObject {
    
}


//账户余额
class AccountBalanceModel {
    
    //获取账户余额
    class func getAccountBalance(_ completionHandler:@escaping (WWValueResponse<NSNumber>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId else {
            return
        }
        
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxMigrantWorkerSalaryPayApply.GetAccountAmount"
        
        let params = ["Method": method, "companyID": companyId, "AccountId": accountId]
        
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON{ (response) in
            if response.result.isSuccess {
                if let dic = response.result.value as? [String: Any] {
                    
                    if let amount = dic["amount"] as? Float{
                        let amountObj = NSNumber.init(value: amount)
                        completionHandler(WWValueResponse.init(value: amountObj, success: true))
                        return
                    }
                }
                
                completionHandler(WWValueResponse.init(success: false, message: "数据分析错误"))
                
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "网络访问出错"))
            }
        }
    }
}

//工资流动模型
class SalaryFlowModel {
    var createTime: Date? //生成时间
    var applyAmount: Double? //资金数量
    var projectName: String? //项目名称
    var companyName: String? //公司名称
    var moneyFlowDetail: String? //资金流动细节
    var changeType: String? //条目类型
    var salaryMonths: String?

    required init(jsonDate: [String: Any] ) {
        if let applyAmount = jsonDate["ApplyAmount"] {
            self.applyAmount = applyAmount as? Double
        }
        
        if let createTime = jsonDate["CreateTime"] {
            let dateString = createTime as! String
            let date = dateStringWithTToDate(dateString: dateString)
            if date != nil {
                self.createTime = date
            }
        }
        
        if let projectName = jsonDate["ProjectName"] {
            self.projectName = projectName as? String
        }
        if let companyName = jsonDate["CompanyName"] {
            self.companyName = companyName as? String
        }
        if let salaryMonths = jsonDate["SalaryMonths"] {
            self.salaryMonths = salaryMonths as? String
        }
        
        self.changeType = jsonDate["ChangeType"] as? String
        
        if self.projectName != nil && self.companyName != nil && self.changeType != nil {
            if self.changeType == "提现"{
                self.moneyFlowDetail = self.changeType!
            }else{
            self.moneyFlowDetail = self.changeType! + "-" + self.projectName!
            }
        }
        
    }
    
    //获取工资流动明细
    class func getSalaryFlowDetail(pageIndex:Int = 1, pageSize: Int = 25,completionHandler:@escaping (WWValueResponse<[SalaryFlowModel]>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId else {
            return
        }
        
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxMigrantWorkerSalaryPayApply.GetAccountChangeDetail"
        let pageIndex = "\(pageIndex)"
        let pageSize = "\(pageSize)"
        let params = ["Method":method, "CompanyID":companyId, "AccountId":accountId, "PageIndex":pageIndex, "PageSize": pageSize]
        
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dic = response.result.value as? [String: AnyObject] {
                    let status = StatusStruct(rootJson: dic)
                    if status.success {
                        let dateJson = dic["Result"]
                        
                        if let dateArray = dateJson as? [[String: Any]] {
                            var models = [SalaryFlowModel]()
                            
                            for item in dateArray {
                                let model = SalaryFlowModel(jsonDate: item)
                                models.append(model)
                            }
                            completionHandler(WWValueResponse.init(value: models, success: true))
                            return
                        }
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
}

//工资请款
class SalaryApplyModel {
    var salaryDate: Date? //请款时间
    var applyAmount = "0" //结算工资,1000,000.00格式
    var workingDays = "0" //结算天数
    var workingHours = "0" //结算工时
    var protocolSalary = "0" //预结算工资
    var realPaySalary = "0" //实际结算工资
    var workedDays = "0"
    
    required init(_ jsonData: [String: AnyObject]) {
        if let salaryDate = jsonData["SalaryDate"] {
            let dateString = salaryDate as! String
            let date = dateStringWithTToDate(dateString: dateString)
            self.salaryDate = date
        }
        if let applyAmount = jsonData["ApplyAmount"] {
            let tempString = "\(applyAmount)"
            let string = Tool.numberToMoney(tempString)
            self.applyAmount = string ?? "0"
        }
        if let protocolSalary = jsonData["ProtocolSalary"] {
            let tempString = "\(protocolSalary)"
            let string = Tool.numberToMoney(tempString)
            self.protocolSalary = string ?? "0"
        }
        if let realPaySalary = jsonData["RealPaySalary"] {
            let tempString = "\(realPaySalary)"
            let string = Tool.numberToMoney(tempString)
            self.realPaySalary = string ?? "0"
        }
        if let workingDays = jsonData["WorkingDays"] {
            self.workingDays = "\(workingDays)"
        }
        if let workingHours = jsonData["WorkingHours"] {
            self.workingHours = "\(workingHours)"
        }
        if let workedDays = jsonData["WorkedDays"] {
            self.workedDays = "\(workedDays)"
        }
    }
    class func getApplyModelRecord(demandBaseMigrantWorkerID: String,completionHandler: @escaping (WWValueResponse<[SalaryApplyModel]>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId else {
            return
        }
        
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxMigrantWorkerSalaryPayApply.GetSalaryApplyRecord"
        
        let params = ["Method": method, "DemandBaseMigrantWorkerID":demandBaseMigrantWorkerID, "CompanyMGID":companyId, "AccountId": accountId]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let valueDic = response.result.value as? [String: AnyObject] {
                    var salaryModels = [SalaryApplyModel]()
                    
                    let status = StatusStruct(rootJson: valueDic)
                    if status.success {
                        let results = valueDic["Result"] as! [[String: AnyObject]]
                        
                        if results.count == 0 {
                            completionHandler(WWValueResponse.init(success: false, message: "获取数据为空"))
                            return
                        }
                        for item in results {
                            let model = SalaryApplyModel.init(item)
                            salaryModels.append(model)
                        }
                        completionHandler(WWValueResponse.init(value: salaryModels, success: true))
                    }
                    else {
                        completionHandler(WWValueResponse.init(success: false, message: status.statusString))
                    }
                }
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "网络请求错误"))
            }
        }
    }
}



/// 工资提现
class SalaryWithdraw: NSObject {
    var projectName: String? //项目名字
    var applyAmount: Float? //金额
    var createTime: Date? //日期
    var MigrantWorkerSalaryDetailID: String? //工资请款ID
    
    required init(_ jsonData: [String: AnyObject]) {
        if let projectName = jsonData["ProjectName"] {
            self.projectName = projectName as? String
        }
        if let applyAmount = jsonData["ApplyAmount"] {
            self.applyAmount = applyAmount as? Float
        }
        if let createTime = jsonData["CreateTime"] {
            let timeWithTString = createTime as! String
            
            let time = dateStringWithTToDate(dateString: timeWithTString)
            self.createTime = time
        }
        
        if let salaryDetailId = jsonData["MigrantWorkerSalaryDetailID"] {
            self.MigrantWorkerSalaryDetailID = salaryDetailId as? String
        }
    }
    
    //获取提现列表
    class func getWihtdrawLists(completionHandler:@escaping (WWValueResponse<[SalaryWithdraw]>) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId else {
            return
        }
        
        let mehtod = "MarTian.MigrantWorkerManage.Handler.AjaxMigrantWorkerSalaryPayApply.GetSalaryEnchashmentView"
        
        let params = ["Method": mehtod, "CompanyID":companyId, "AccountId":accountId, "PageIndex":"1", "PageSize":"25"]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let value = response.result.value as? [String: AnyObject] {
                    let status = StatusStruct(rootJson: value)
                    if status.success {
                        let jsonArr = value["Result"] as? [[String: AnyObject]]
                        guard jsonArr != nil else {
                            
                            return
                        }
                        
                        var salaryWithdrawArr = [SalaryWithdraw]()
                        for item in jsonArr! {
                            let model = SalaryWithdraw.init(item)
                            salaryWithdrawArr.append(model)
                        }
                        completionHandler(WWValueResponse.init(value: salaryWithdrawArr, success: true))
                        return
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
                
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "访问网络错误"))
            }
        }
    }
    
    
    /// 提现
    ///
    /// - Parameters:
    ///   - guid:
    ///   - amount: 请款工资金额合计
    ///   - bankCardId: 选择的银行卡ID,不是银行卡号
    ///   - orderNo: 单据编号
    ///   - migrantWorkerSalaryDetailID: 选择的工资请款iD
    ///   - completionHandler:
    class func withdraw(_ guid: String, amount: Float, bankCardId: String,orderNo: String, migrantWorkerSalaryDetailIDs: [String], completionHandler: @escaping (WWResponse) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "KouFine.Handler.Core.AjaxOperate.SubmitProcess"
        let pageName = "KouFine.Container.Form"
        let orderConfigId = "7779fe7e-0dbe-6ae7-135a-c3d5a3a5bdd4"
        let approvalNote = "提交审批"
        let carbonList = ""
        
        //form
        let migrantWorkerSalaryCardDic = ["ID":bankCardId]
        let form = ["EnchashmentAmount": amount, "OrderNo":orderNo, "MigrantWorkerSalaryCards":migrantWorkerSalaryCardDic] as [String : Any]
        
        //TiXianMingXi
        var mingxiArr = [[String: Any]]()
        for item in migrantWorkerSalaryDetailIDs {
            let dic = ["ID": guid, "MigrantWorkerSalaryDetailID": item, "Operate":1] as [String : Any]
            mingxiArr.append(dic)
        }
        
        let jsonData = ["ID": guid, "Form":form, "TiXianMingXi":mingxiArr] as [String : Any]
        let jsonDataString = getJSONStringFromDictionary(dictionary: jsonData as NSDictionary)
        
        let params = ["pageName":pageName, "Method": method, "carbonList":carbonList, "approvalNote":approvalNote, "orderConfigId":orderConfigId, "orderId":guid, "AccountId": accountId, "jsonData": jsonDataString]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                if let value = response.result.value {
                    if value == "OK" {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else
                    {
                        completionHandler(WWResponse.init(success: false, message: value))
                    }
                    return
                }
                completionHandler(WWResponse.init(success: false, message: "数据有异常"))
            }
            else {
                
                completionHandler(WWResponse.init(success: false, message: "网络访问错误！"))
            }
        }
    }
    
    
}

class PaymentPassword {
    class func setupPaymentPassword(_ phoneNumber: String, verifycode: String, payPassword: String, completionHandler:@escaping (WWResponse) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        let method = "MarTian.WebSitePortal.Handler.AjaxSignUp.SetPayPwdForApp"
        
        let params = ["Method": method, "phoneNumber": phoneNumber, "verifycode":verifycode, "payPasswork": payPassword, "AccountId": accountId]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    if let status = dict["Status"] as? String {
                        if status == "OK" {
                            completionHandler(WWResponse.init(success: true))
                        }
                        else {
                            let msg = dict["Msg"] as? String
                            completionHandler(WWResponse.init(success: false, message: msg))
                        }
                        return
                    }
                }
                completionHandler(WWResponse.init(success: false, message: "数据解析出错"))
            }
            else {
                
                completionHandler(WWResponse.init(success: false, message: "网络错误"))
            }
        }
    }
    
    enum CheckPaymentPasswordResult {
        case success //验证成功
        case wrongPassword //错误密码
        case unSet //支付密码未设置
        case unKnow //未知错误，网络错误
    }
    
    //验证支付密码。           response的字符串会返回status。OK：密码已设置，ERROR：密码为设置
    class func checkPaymentPassword(_ password: String,completionHandler:@escaping (WWValueResponse<CheckPaymentPasswordResult>) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        let method = "MarTian.WebSitePortal.Handler.AjaxSignUp.CheckPayPwd"
        
        let params = ["Method": method, "payPasswork":password, "AccountId":accountId]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    if let status = dict["Status"] as? String {
                        
                        var checkResult = CheckPaymentPasswordResult.unKnow
                        
                        if status == "OK" {
                            if let result = dict["Result"] {
                                let resultString = "\(result)"
                                if resultString == "0" {
                                    checkResult = .wrongPassword
                                    completionHandler(WWValueResponse.init(value: checkResult, message: dict["Msg"] as! String, success: false))
                                }
                                if resultString == "1" {
                                    checkResult = .success
                                    completionHandler(WWValueResponse.init(value: checkResult, message: "密码设置成功", success: true))
                                }
                            }
                        }
                        if status == "ERROR" {
                            checkResult = .unSet
                            completionHandler(WWValueResponse.init(value: checkResult, message: "交易密码未设置", success: false))
                        }
                        return
                    }
                }
                completionHandler(WWValueResponse.init(value: .unKnow, message: "网络解析错误", success: false))
            }
            else {
                
                completionHandler(WWValueResponse.init(value: .unKnow, message: "网络解析错误", success: false))
            }
        }
    }
}

